/**
 * @ClassName: 双端队列
 * @author:
 * @Description:
 * @Date
 **/
public class Deque<E> {
    private E[] data;
    private int front, tail;
    private int size;

    public Deque(int capacity) {
        data = (E[]) new Object[capacity]; // 由于使用 size，我们的 Deque 实现不浪费空间
        front = 0;
        tail = 0;
        size = 0;
    }

    public Deque() {
        this(10);
    }

    public int getCapacity() {
        return data.length;
    }


    public void addFront(E e) {
        if (size == getSize()) {
            resize(getCapacity() * 2);
        }
        //先算出front的位置
        front = front == 0 ? data.length - 1 : front - 1;
        data[front] = e;
        size++;
    }

    private void resize(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            //为了防止数组越界
            newData[i] = data[(i + front) % data.length];
        }
        front = 0;
        data = newData;
        tail = size;
    }

    public E removeFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("queue is empty");
        }
        E ret = data[front];
        data[front] = null;
        //弹出队首的元素，front本身要加1，但要防止数组越界问题
        front = (front + 1) % data.length;
        size--;
        if (size == getCapacity() / 4 && getCapacity() / 2 != 0) {
            resize(getCapacity() / 2);
        }
        return ret;
    }

    public void addLast(E e) {
        if (size == getSize()) {
            resize(getCapacity() * 2);
        }
        data[tail] = e;
        //防止tail加1后数组越界
        tail = (tail + 1) % data.length;
        size++;
    }

    public E removeLast() {
        if (isEmpty()) {
            throw new IllegalArgumentException("dequeue is empty");
        }
        //先计算tail位置
        tail = tail == 0 ? data.length - 1 : tail - 1;
        E ret = data[tail];
        data[tail] = null;
        if (getSize() == getCapacity() / 4 && getCapacity() / 2 != 0) {
            resize(getCapacity() / 2);
        }
        return ret;
    }


    public E getFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("dequeue is empty");
        }
        return data[front];
    }

    public E getLast() {
        //获得真正的tail
        int index = tail == 0 ? data.length - 1 : tail - 1;
        return data[index];
    }

    public int getSize() {
        return size;
    }


    public boolean isEmpty() {
        return size == 0;
    }
}
